﻿using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.FrameEntity;
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SysFramework;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tools;

namespace BLL
{
    /// <summary>
    /// 客商信息处理类
    /// </summary>
    public class CustomBLL: PubMethod
    {
        ReturnResult rsl;
        Commands cmd;
        SystemManagement sysBLL;
        OutBaseHelper outBase;
        public ILog log = LogManager.GetLogger(typeof(CustomBLL));

        List<OperateModel> operList;
        OperateModel oper;

        public CustomBLL()
        {
            rsl = new ReturnResult();
            cmd = new Commands();
            sysBLL = new SystemManagement();
            outBase = new OutBaseHelper();
 
        }
        /// <summary>
        /// 客商数据同步方法
        /// </summary>
        /// <param name="dataType"></param>
        /// <param name="isAuto"></param>
        /// <returns></returns>
        public ReturnResult SyncCustom(string userCode,string baseCode,string dataType,bool isAuto = false)
        {
            rsl = new ReturnResult();
            try
            {
                rsl = this.SyncCuClasss(userCode, baseCode, dataType);
                if (rsl.Result)
                {
                    rsl = this.SyncCustomData(userCode, baseCode, dataType,isAuto);
                }
                
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 客户数据同步方法
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="baseCode"></param>
        /// <param name="dataType"></param>
        /// <param name="isAuto"></param>
        /// <returns></returns>
        public ReturnResult SyncCustomData(string userCode, string baseCode, string dataType,bool isAuto)
        {
            rsl = new ReturnResult();
      

            try
            {
                if (string.IsNullOrWhiteSpace(baseCode))
                {
                    rsl.Message = "数据库编码获取失败";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
               
                var table =this.ErpSupCuData(dataType,baseCode,isAuto);

                sb.Clear();
                sb.Append("select * from fun_Customs_info where dataType='"+ dataType +"' and baseCode='" + baseCode + "'");
                var qTable = cmd.GetDataTable(sb.ToString());//数据

                List<OperateModel> list = new List<OperateModel>();
                DbCustomer cus;
                OperateModel oper;
               
                if (table.Rows.Count > 0)
                {
                    #region 构建数据
                    foreach (DataRow r in table.Rows)
                    {
                        oper = new OperateModel();
                        cus = new DbCustomer();
                        var dr = qTable.Select("cuCode='" + r["cCode"].ToString().Trim() + "'");
                        cus.isDel = 0;
                        cus.isSync = "Y";
                        cus.cuCode = r["cCode"].ToString(); //h l j l h b  .Replace(" ","")
                        cus.cuName = r["cName"].ToString();
                        cus.cuType = r["cType"].ToString();
                        cus.baseCode = baseCode;
                        cus.arddress = r["cAddress"].ToString();
                        cus.recArddress = r["cRecAddress"].ToString();
                        cus.dataType = dataType;
                        cus.phone = r["cPhone"].ToString();
                        if (string.IsNullOrWhiteSpace(r["cStopDate"].ToString()) || DateTime.Parse(r["cStopDate"].ToString()).Year < 2022)
                        {
                            cus.status = "Y";
                        }
                        else
                        {
                            cus.status = "N";
                        }
                        if (dr.Length < 1)
                        {
                            cus.createtime = getNow();
                            cus.createuser = userCode;
                            oper.Types = OperateModel.OperateType.Add;
                        }
                        else
                        {
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Conditions = "cuCode,baseCode,dataType";
                        }

                        oper.Data = cus;
                        list.Add(oper);
                    }
                    #endregion
                }
                else
                {
                    rsl.Message = "更新完成(无数据)";
                    rsl.Result = true;
                }
                string msg = "";
                sysBLL.SubmitSyncData(list, "客商数据同步", ref msg);
                if (string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Result = true;
                }
                else
                {
                    rsl.Result = false;
                    rsl.Message = msg;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
      /// <summary>
      /// 客商大类数据同步方法
      /// </summary>
      /// <param name="userCode">人员</param>
      /// <param name="baseCode">账套号</param>
      /// <param name="dataType">数据类型</param>
      /// <returns></returns>
        private ReturnResult SyncCuClasss(string userCode,string baseCode,string dataType)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {

                StringBuilder sb = new StringBuilder();
             
                var out_cuTypeTable =this.ErpSupCuClass(dataType,baseCode);
                sb.Clear();
                sb.Append("select * from fun_CommonTree_info where trType='" + dataType + "'");
                var cuTypeTable = cmd.GetDataTable(sb.ToString());
          

                var dr = out_cuTypeTable.Select("cGrade =1");//获取第一级菜单
                foreach (DataRow r in dr)
                {
                    oper = new OperateModel();
                    this.createCuClassPar(r, ref oper, cuTypeTable, baseCode,userCode, dataType+"0",dataType);
                    operList.Add(oper);
                    this.CallBackCuClass(out_cuTypeTable, 2, r["cCode"].ToString(), ref operList, cuTypeTable, baseCode, userCode,dataType);
                }
                var qdr = cuTypeTable.Select("trCode='"+ dataType+"0" + "'");
                if (qdr.Length < 1)
                {
                    DbCommomTree cTree = new DbCommomTree();
                    if (dataType == "Sp")
                    {
                        cTree.trName = "供应商类";
                    }
                    else {
                        cTree.trName = "客户大类";
                    }
                    cTree.memo = "客商信息";
                    cTree.trType = dataType;
                    cTree.trCode = dataType+"0";
                    cTree.isdel = 0;
                    oper = new OperateModel();
                    oper.Data = cTree;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// ERP客商大类数据(U8)
        /// </summary>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        private DataTable ErpSupCuClass(string dataType,string baseCode)
        {
            StringBuilder sb = new StringBuilder();
            if (dataType == "Cu")
            {
                //sb.Append("select cCusCode cCode,cCusName cName,cCCCode cType,cCusPPerson cChanager,");//客商编码、客商名称、大类编码,专员
                //sb.Append("cCusOAddress cRecAddress,cCusAddress cAddress,dEndDate cStopDate from Customer ");//停用日期,发货地址，公司地址
                sb.Append("select cCCCode cCode,cCCName cName,iCCGrade cGrade from CustomerClass");
            }
            else if (dataType == "Sp")
            {
                sb.Append("select cVCCode cCode,cVCName cName,iVCGrade cGrade from VendorClass");
            }
            return outBase.getData(sb.ToString(), baseCode);
        }
        /// <summary>
        /// ERP客商档案数据(U8)
        /// </summary>
        /// <param name="dataType"></param>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        private DataTable ErpSupCuData(string dataType, string baseCode,bool isAuto)
        {
            StringBuilder sb = new StringBuilder();
            if (dataType == "Cu")
            {
                sb.Append("select cCusCode cCode,cCusName cName,cCCCode cType,cCusPPerson cChanager,cCusPhone cPhone,");//客商编码、客商名称、大类编码,专员
                sb.Append("cCusOAddress cRecAddress,cCusAddress cAddress,dEndDate cStopDate from Customer ");//停用日期,发货地址，公司地址
                sb.Append(" where cCusName not like '%停用%' ");
            }
            else if (dataType == "Sp")
            {
                sb.Append("select cVenCode cCode,cVenName cName,cVCCode cType,'' cChanager,cVenPhone cPhone,");//客商编码、客商名称、大类编码,专员
                sb.Append("'' cRecAddress,cVenAddress cAddress,dEndDate cStopDate from Vendor ");//停用日期,发货地址，公司地址
                sb.Append(" where cVenName not like '%停用%' ");
            }
          
            if (!isAuto)
            {
                string value = string.Format("-{0}", Tools.ConfigReader.Reader["SyncInventoDay"]);
                string qydate = DateTime.Now.AddDays(double.Parse(value)).ToString("yyyy-MM-dd");
                sb.Append(" and dModifyDate>='" + qydate + "'");//修改时间
            }
            return outBase.getData(sb.ToString(), baseCode);
        }
        /// <summary>
        /// 创建客户大类参数
        /// </summary>
        /// <param name="r"></param>
        /// <param name="oper"></param>
        /// <param name="qTable"></param>
        /// <param name="baseCode"></param>
        /// <param name="isAuto"></param>
        /// <param name="parentCode"></param>
        private void createCuClassPar(DataRow r, ref OperateModel oper, DataTable qTable, string baseCode, string userCode, string parentCode,string dataType)
        {
            var query = qTable.Select("trCode='" + r["cCode"].ToString() + "' and baseCode='"+ baseCode +"'");
            bool isAdd = true;
            if (query.Length > 0)
            {
                isAdd = false;
            }
            DbCommomTree cTree = new DbCommomTree();
            cTree.trName = r["cName"].ToString();
            cTree.trCode = r["cCode"].ToString();
            cTree.isdel = 0;
            cTree.parentCode = parentCode;
            cTree.trType = dataType;
            cTree.baseCode = baseCode;
            if (isAdd)
            {
                #region 只有在添加状态下 下列值才会添加
                cTree.createtime = getNow();
                    cTree.createuser =userCode;
               
                #endregion
                oper.Types = OperateModel.OperateType.Add;
            }
            else
            {
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "trCode,baseCode,trType";
            }
            oper.Data = cTree;
        }
      /// <summary>
      /// 递归
      /// </summary>
      /// <param name="dt"></param>
      /// <param name="gradeNum"></param>
      /// <param name="cCode"></param>
      /// <param name="list"></param>
      /// <param name="sysTable"></param>
      /// <param name="baseCode"></param>
      /// <param name="isAuto"></param>
        private void CallBackCuClass(DataTable dt, int gradeNum, string cCode, ref List<OperateModel> list, DataTable sysTable, string baseCode, string userCode,string dataType)
        {
            var dr = dt.Select("cCode like '" + cCode + "%' and cGrade=" + gradeNum);
            if (dr.Length > 0)
            {
                OperateModel oper;

                foreach (DataRow r in dr)
                {
                    oper = new OperateModel();
                    createCuClassPar(r, ref oper, sysTable, baseCode, userCode, cCode,dataType);
                    list.Add(oper);
                    CallBackCuClass(dt, gradeNum + 1, r["cCode"].ToString(), ref list, sysTable, baseCode, userCode,dataType);
                }
            }
        }
        /// <summary>
        /// 通用导航大类
        /// </summary>
        /// <param name="dataType"></param>
        /// <returns></returns>
        public ReturnResult TreeClassNavigation(string baseCode,string dataType)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_CommonTree_info where trType='"+ dataType + "'");
                sb.Append(" and isdel=0 and baseCode='" + baseCode + "' ");
                sb.Append(" or (parentCode is null and trType='" + dataType + "')");
                var table = cmd.GetDataTable(sb.ToString());//获取全部有效菜单信息

                List<Dictionary<string, object>> menuList = new List<Dictionary<string, object>>();
                #region 构建数据
                var fMenu = table.Select("parentCode is null");//获取所有父级菜单
                for (int i = 0; i < fMenu.Length; i++)
                {
                    var fdic = new Dictionary<string, object>();
                    fdic["title"] = string.Format("{0}({1})", fMenu[i]["trName"].ToString(), fMenu[i]["trCode"].ToString());
                    fdic["id"] = fMenu[i]["trCode"].ToString();
                    fdic["spread"] = "true";

                    #region 子菜单
                    List<Dictionary<string, object>> cList = new List<Dictionary<string, object>>();
                    this.ChildUrl(table, fMenu[i]["trCode"].ToString(), ref cList);
                    fdic["children"] = cList;
                    #endregion
                    menuList.Add(fdic);
                }
                #endregion
                rsl.Data = menuList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        private void ChildUrl(DataTable table, string cCode, ref List<Dictionary<string, object>> chlist)
        {
            var dr = table.Select("parentCode='" + cCode + "'");
            if (dr.Length > 0)
            {
                for (int x = 0; x < dr.Length; x++)
                {
                    List<Dictionary<string, object>> tempList = new List<Dictionary<string, object>>();
                    var cdic = new Dictionary<string, object>();
                    cdic["title"] = string.Format("{0}({1})", dr[x]["trName"].ToString(), dr[x]["trCode"].ToString());
                    cdic["id"] = dr[x]["trCode"].ToString();
                    ChildUrl(table, dr[x]["trCode"].ToString(), ref tempList);
                    // cdic["spread"] = "true";
                    cdic["children"] = tempList;
                    chlist.Add(cdic);
                }
            }
        }
        /// <summary>
        /// 客商数据列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getCustomDataList(string baseCode,string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                sb.Append("  isdel=0 and baseCode='" + baseCode + "'");
                sb = CreateSelectCondition(sb,condition,"cuType-Cu0");
                
                var list = cmd.PageList("fun_Customs_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = list;
                //rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 查找供应商
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public ReturnResult SearchVendors(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var filterDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

                var searchSb = new StringBuilder();

                searchSb.Append("select top 100 * from fun_Customs_info where isdel = 0 and dataType='Sp' ");  //and baseCode='" + filterDic["baseCode"].ToString() + "'

                var whereSb = new StringBuilder();
                foreach (var key in filterDic.Keys)
                {
                    var filterValue = filterDic[key];

                    if (!string.IsNullOrEmpty(filterValue))
                    {
                        whereSb.Append(" and ");
                        whereSb.Append(key + " like '%");
                        whereSb.Append(filterValue);
                        whereSb.Append("%' ");
                    }
                }

                searchSb.Append(whereSb.ToString());

                var dt = cmd.GetDataTable(searchSb.ToString());

                var returnListDic = cmd.TableToDictionary(dt);

                rsl.Result = true;
                rsl.Data = returnListDic;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


    }
}
